package psi.services;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import psi.common.PSISessionKit;

/**
 * 业务日志 Service
 * 
 * @author 李静波
 *
 */
public class BizlogService extends PSIBaseService {

	public Record logList(Record params) {
		int start = Integer.parseInt(params.getStr("start"));
		int limit = Integer.parseInt(params.getStr("limit"));

		String sql = "";
		sql += " select b.id, u.login_name, u.name, b.ip, b.info, b.date_created, b.log_category ";
		sql += " from t_biz_log b, t_user u ";
		sql += " where b.user_id = u.id ";
		sql += " order by b.date_created desc ";
		sql += " limit ? , ? ";
		List<Record> data = Db.find(sql, start, limit);

		List<Record> logs = new ArrayList<Record>();
		for (Record r : data) {
			Record item = new Record();
			item.set("id", r.getLong("id"));
			item.set("loginName", r.getStr("login_name"));
			item.set("userName", r.getStr("name"));
			item.set("ip", r.getStr("ip"));
			item.set("content", r.getStr("info"));
			item.set("logCategory", r.getStr("log_category"));
			item.set("dt", r.getTimestamp("date_created"));

			logs.add(item);
		}

		sql = "";
		sql += " select count(*) as cnt ";
		sql += " from t_biz_log b, t_user u ";
		sql += " where b.user_id = u.id";
		long cnt = Db.queryLong(sql);

		return new Record().set("logs", logs).set("totalCount", cnt);
	}

	public void insertBizlog(String log, String category) {
		UserService us = new UserService();
		String userId = us.getLoginUserId();
		if (userId == null) {
			return;
		}

		String sql = "insert into t_biz_log (user_id, info, ip, date_created, log_category) ";
		sql += " values (?, ?, ?,  now(), ?)";

		Db.update(sql, userId, log, getClientIP(), category);
	}

	private String getClientIP() {
		String ip = (String) PSISessionKit.get().getAttribute("login_user_ip");
		if (ip == null) {
			ip = "";
		}
		
		return ip;
	}
}
